package com.lanyan.web.controller.courier;

import com.alibaba.fastjson2.JSONObject;
import com.lanyan.common.annotation.Log;
import com.lanyan.common.annotation.RepeatSubmit;
import com.lanyan.common.core.controller.BaseController;
import com.lanyan.common.core.domain.AjaxResult;
import com.lanyan.common.core.domain.PageR;
import com.lanyan.common.core.domain.R;
import com.lanyan.common.enums.BusinessType;
import com.lanyan.common.utils.SecurityUtils;
import com.lanyan.common.utils.StringUtils;
import com.lanyan.common.utils.wx.WxAppletUserInfo;
import com.lanyan.framework.web.service.SysLoginService;
import com.lanyan.framework.web.service.TokenService;
import com.lanyan.system.domain.Account;
import com.lanyan.system.domain.Building;
import com.lanyan.system.domain.Courier;
import com.lanyan.system.domain.Estate;
import com.lanyan.system.domain.vo.BuildingVo;
import com.lanyan.system.domain.vo.CourierVo;
import com.lanyan.system.service.IBuildingService;
import com.lanyan.system.service.ICourierService;
import com.lanyan.system.service.IEstateService;
import com.lanyan.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 配送员Controller
 *
 * @author lanyan
 * @date 2024-11-26
 */
@RestController
@Api(tags = {"配送员" })
@RequestMapping("/courier")
public class CourierLoginController extends BaseController {
    @Autowired
    private ICourierService courierService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private IEstateService estateService;
    @Autowired
    private IBuildingService buildingService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysConfigService configService;

    @ResponseBody
    @GetMapping("getOpenId")
    @ApiOperation(value = "getOpenId")
    public AjaxResult getOpenId(HttpServletRequest request, String code) {
        JSONObject jsonObject = WxAppletUserInfo.getSessionKeyOropenid(
                code,
                configService.selectConfigByKey("wx.ps.appId"),
                configService.selectConfigByKey("wx.ps.secret")
        );
        String openId = (String) jsonObject.get("openid");
//
        HttpSession session = request.getSession();//创建session
        Object session_key = jsonObject.get("session_key");
        session.setAttribute("sessionkey",session_key);
//        openId = "oM7ur690JoYFX_RC_0VA1j7rDKBw";
        if (null == openId) {
            return  AjaxResult.error(201, "失败");
        } else {
            Map result =new HashMap();
            result.put("openId",openId);
            result.put("sessionKey", session_key);
            return AjaxResult.success(result);
        }
    }

    @GetMapping("login")
    @ApiOperation(value = "login")
    public AjaxResult login(String name, String password,String openId) {
        if (StringUtils.isEmpty(openId)){
            return error("请先授权");
        }
        String token = loginService.courierLogin(name, password);
        Courier courier = courierService.lambdaQuery()
                .eq(CourierVo::getDelFlag, "0")
                .eq(CourierVo::getLoginName, name)
                .eq(CourierVo::getLoginPassword, password)
                .one();
        if (StringUtils.isNotEmpty(courier.getToken())){
            tokenService.delLoginUserByToken(courier.getToken());
        }
        courierService.lambdaUpdate()
                .eq(CourierVo::getCourierId,courier.getCourierId())
                .set(CourierVo::getToken,token)
                .set(CourierVo::getOpenId,openId)
                .update();
        return AjaxResult.success("获取成功",token);
    }

    @GetMapping("info")
    @ApiOperation(value = "info")
    public AjaxResult info() {
        Courier courier = courierService.getById(SecurityUtils.getUserId());
        Estate estate = estateService.getById(courier.getEstateId());
        courier.setTakeEstate(estate.getName());
        List<Building> buildingList = buildingService.lambdaQuery()
                .eq(BuildingVo::getDelFlag, "0")
                .eq(BuildingVo::getCourierId, courier.getCourierId())
                .orderByAsc(BuildingVo::getName)
                .list();
        StringBuffer stringBuffer = new StringBuffer();
        for (Building building : buildingList) {
            stringBuffer.append(building.getName());
            stringBuffer.append("、");
        }
        if (stringBuffer.length() > 0){
            String string = stringBuffer.substring(0, stringBuffer.length() - 1).toString();
            courier.setTakeBuilding(string);
        }
        return success(courier);
    }

    @PostMapping("update")
    @ApiOperation(value = "修改信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "昵称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "avatar", value = "头像", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "phone", value = "电话", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "state", value = "状态（0下班 1上班）", dataType = "String", dataTypeClass = String.class),
    })
    public AjaxResult update(@RequestBody Courier courier) {
        courier.setCourierId(SecurityUtils.getUserId());
        return success(courierService.updateById(courier));
    }

}
